﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ScrumTime.Models;

namespace ScrumTime.ViewModels
{
    public class ProductCollectionViewModel 
    {

        private bool _cantAddProduct;

        public List<ProductViewModel> ProductViewModels { get; set; }

        public ProductCollectionViewModel()
        {
            
        }

        public bool CanAddProduct() {
            return this._cantAddProduct;
        }

        public static ProductCollectionViewModel BuildByNameAlphabetical(int currentProductId, bool cantAddProduct, String user_guid)
        {
            ScrumTimeEntities scrumTimeEntities = new ScrumTimeEntities();   
            ProductCollectionViewModel productCollectionViewModel = new ProductCollectionViewModel()
            {
                ProductViewModels = new List<ProductViewModel>()
            };
            productCollectionViewModel._cantAddProduct = cantAddProduct;

            if (cantAddProduct)
            {
                // si puede agregar productos, simplemente agregamos todos los productos existentes
                // puesto q el usuario es un administrador
                var results = from p in scrumTimeEntities.Products
                              orderby p.Name ascending
                              select p;
                foreach (Product product in results)
                {
                    ProductViewModel productViewModel = new ProductViewModel()
                    {
                        IsCurrent = (product.ProductId == currentProductId) ? true : false,
                        ProductModel = product
                    };
                    productCollectionViewModel.ProductViewModels.Add(productViewModel);
                }
            }
            else { 
                //caso contrario, listamos los productos a los q este usuario tiene acceso
                ScrumTime.Services.UserService userService = new ScrumTime.Services.UserService(scrumTimeEntities);

                ScrumTime.Models.User user =  userService.GetUserByGuid(user_guid);
                foreach (Product product in user.Products)
                {
                    ProductViewModel productViewModel = new ProductViewModel()
                    {
                        IsCurrent = (product.ProductId == currentProductId) ? true : false,
                        ProductModel = product
                    };
                    productCollectionViewModel.ProductViewModels.Add(productViewModel);
                }
            }
            
            return productCollectionViewModel;
        }
    }
}